//
//  V2MenuSectionView.m
//  v2ex-iOS
//
//  Created by Singro on 3/30/14.
//  Copyright (c) 2014 Singro. All rights reserved.
//

#import "JrdMenuSectionView.h"

#import "SCActionSheet.h"
#import "SCActionSheetButton.h"

#import "JrdMenuSectionCell.h"
#import "JrdDatamanager.h"
#import "JrdMeViewController.h"
#import "JrdSettingManager.h"
static CGFloat const kAvatarHeight = 39.f;

@interface JrdMenuSectionView () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIImageView *avatarImageView;
@property (nonatomic, strong) UIButton    *avatarButton;
@property (nonatomic, strong) UIImageView *divideImageView;
@property (nonatomic, strong) UILabel     *usernameLabel;

@property (nonatomic, strong) SCActionSheet      *actionSheet;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray     *sectionImageNameArray;
@property (nonatomic, strong) NSArray     *sectionTitleArray;

@end

@implementation JrdMenuSectionView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        
        self.sectionImageNameArray = @[@"ico_mylearnings", @"ico_offline", @"ico_coursecenter", /*@"ico_username",*/ @"ico_setting"];
//        self.sectionTitleArray = @[@"Latest", @"Categories", @"Nodes", @"Favorite", @"Notification", @"Profile"];
        self.sectionTitleArray = @[NSLocalizedString(@"v2_my_study", nil), NSLocalizedString(@"v2_offline_course", nil), NSLocalizedString(@"v2_select_center", nil), /*NSLocalizedString(@"v2_me", nil),*/ NSLocalizedString(@"v2_settings", nil)];

        [self configureTableView];
        [self configureProfileView];
        [self configureSearchView];
        [self configureNotifications];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveThemeChangeNotification) name:kThemeDidChangeNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(updatePickImageExt)
                                                     name:kPickImageNotification
                                                   object:nil];

//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveUpdateCheckInBadgeNotification) name:kUpdateCheckInBadgeNotification object:nil];

    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)updatePickImage{
    //image picker
    //获取Documents文件夹目录
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path objectAtIndex:0];
    //指定新建文件夹路径
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    //保存图片的路径
    NSString* imagePath = [imageDocPath stringByAppendingPathComponent:@"image.png"];
    UIImage *image=[UIImage imageWithContentsOfFile:imagePath];
    self.avatarImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ico_username"]];

    if(nil == image){
        
    }else{
        [self.avatarImageView setImage:image];
    }

}

- (void)updatePickImageExt{
    if(nil == self.avatarImageView){
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{

    [self.avatarImageView removeFromSuperview];
    //image picker
    //获取Documents文件夹目录
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path objectAtIndex:0];
    //指定新建文件夹路径
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    //保存图片的路径
    NSString* imagePath = [imageDocPath stringByAppendingPathComponent:@"image.png"];
    UIImage *image=[UIImage imageWithContentsOfFile:imagePath];
    self.avatarImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ico_username"]];
    
    if(nil == image){
        
    }else{
        [self.avatarImageView setImage:image];
    }
    self.avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:self.avatarImageView];
    self.avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:self.avatarImageView];
    
    self.avatarImageView.frame = (CGRect){23, 50, kAvatarHeight, kAvatarHeight};
    self.avatarImageView.userInteractionEnabled = YES;
    
    CGFloat cornerRadius = kAvatarHeight* .5;
    self.avatarImageView.layer.masksToBounds = YES;
    self.avatarImageView.layer.cornerRadius = cornerRadius;
    [self addSubview:self.avatarButton];
    [self.avatarButton addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];
    [self.avatarButton addTarget:self action:@selector(touchUp) forControlEvents:UIControlEventTouchUpInside];
    });
}   

- (void)configureTableView {
    self.tableView                 = [[UITableView alloc] initWithFrame:CGRectZero];
    self.tableView.backgroundColor = [UIColor colorWithRed:200 green:200 blue:200 alpha:1.0];
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate        = self;
    self.tableView.dataSource      = self;
    self.tableView.contentInsetTop = 120;
    [self addSubview:self.tableView];
    
}

- (void)configureProfileView {
    [self updatePickImage];
    self.avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:self.avatarImageView];

    self.avatarImageView.frame = (CGRect){23, 50, kAvatarHeight, kAvatarHeight};
    self.avatarImageView.userInteractionEnabled = YES;
    
    CGFloat cornerRadius = kAvatarHeight* .5;
    self.avatarImageView.layer.masksToBounds = YES;
    self.avatarImageView.layer.cornerRadius = cornerRadius;
    
    self.usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(23 + 20 +kAvatarHeight, 50, 100, kAvatarHeight)];
    [self.usernameLabel setFont:[UIFont systemFontOfSize:18.f]];
    self.usernameLabel.text  = [JrdDatamanager manager].user.userName;
    [self addSubview:self.usernameLabel];
    
    self.avatarImageView.alpha = kSetting.imageViewAlphaForCurrentTheme;
    
    self.avatarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:self.avatarButton];
    
    self.divideImageView = [[UIImageView alloc] init];
    self.divideImageView.backgroundColor = kLineColorBlackDark;
    self.divideImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.divideImageView.clipsToBounds = YES;
    [self.avatarButton addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];
    [self.avatarButton addTarget:self action:@selector(touchUp) forControlEvents:UIControlEventTouchUpInside];

    
    // Handles
    /*[self.avatarButton bk_addEventHandler:^(id sender) {
        self.avatarImageView.image =[UIImage imageNamed:@"ico_username"];
        self.didSelectedIndexBlock(10);
    } forControlEvents:UIControlEventTouchUpInside];
    
    [self.avatarButton bk_addEventHandler:^(id sender) {
        self.avatarImageView.image = [self grayImage:[UIImage imageNamed:@"ico_username"]];
        self.didSelectedIndexBlock(10);
    } forControlEvents:UIControlEventTouchDragInside];*/

}

- (void)touchDown{
    self.avatarButton.backgroundColor =[UIColor colorWithRed:(200)/255.0 green:(200)/255.0 blue:(200)/255.0 alpha:0.5];
    //self.avatarImageView.backgroundColor = JRD_RGB(208, 30, 38);//[UIColor redColor];
}

- (void)touchUp{
    self.avatarButton.backgroundColor = [UIColor clearColor];
    self.didSelectedIndexBlock(10);
}

- (void)buttonpress1{
    NSLog(@"buttonpress1");
}
- (void)configureSearchView {
    
    
    
    
}

- (void)configureNotifications {
    
    @weakify(self);
    [[NSNotificationCenter defaultCenter] addObserverForName:kLoginSuccessNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
        @strongify(self);
        
        //[self.avatarImageView setImageWithURL:[NSURL URLWithString:[V2DataManager manager].user.member.memberAvatarLarge] placeholderImage:[UIImage imageNamed:@"avatar_default"]];
        self.avatarImageView.layer.borderColor = RGB(0x8a8a8a, 0.1).CGColor;

    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:kLogoutSuccessNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
        @strongify(self);
        
        //[self.avatarImageView setImageWithURL:[NSURL URLWithString:[V2DataManager manager].user.member.memberAvatarLarge] placeholderImage:[UIImage imageNamed:@"avatar_default"]];
        self.avatarImageView.layer.borderColor = RGB(0x8a8a8a, 1.0).CGColor;
        
    }];

}

-(UIImage *)grayImage:(UIImage *)sourceImage
{
    int bitmapInfo = kCGImageAlphaNone;
    int width = sourceImage.size.width;
    int height = sourceImage.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate (nil,
                                                  width,
                                                  height,
                                                  8,      // bits per component
                                                  0,
                                                  colorSpace,
                                                  bitmapInfo);
    CGColorSpaceRelease(colorSpace);
    if (context == NULL) {
        return nil;
    }
    CGContextDrawImage(context,
                       CGRectMake(0, 0, width, height), sourceImage.CGImage);
    UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
    CGContextRelease(context);
    return grayImage;
}
#pragma mark - Layout

- (void)layoutSubviews {
    
//    CGFloat spaceHeight = (self.tableView.contentInsetTop - kAvatarHeight) / 3.0;
    self.avatarImageView.frame = (CGRect){23, 50, kAvatarHeight, kAvatarHeight};
    self.avatarButton.frame = (CGRect){0, 30, self.width,kAvatarHeight+40};//self.avatarImageView.frame;zlwu
//    self.divideImageView.frame = (CGRect){80, kAvatarHeight + 50, 80, 0.5};
    self.divideImageView.frame = (CGRect){-self.width, kAvatarHeight + 50, self.width * 2, 0.5};
    self.tableView.frame = (CGRect){0, 0, self.width, self.height};
    
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:[JrdSettingManager manager].selectedSectionIndex inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
}

#pragma mark - Setters

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    
    if (selectedIndex < self.sectionTitleArray.count) {
        _selectedIndex = selectedIndex;
        
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
        
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = - scrollView.contentOffsetY;
    
    self.avatarImageView.y = 50 - (scrollView.contentInsetTop - offsetY) / 1.7;
    self.avatarButton.frame = self.avatarImageView.frame;

    self.divideImageView.y = self.avatarImageView.y + kAvatarHeight + (offsetY - (self.avatarImageView.y + kAvatarHeight)) / 2.0 + fabs(offsetY - self.tableView.contentInsetTop)/self.tableView.contentInsetTop * 8.0 + 10;
    
    
}

#pragma mark - TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sectionTitleArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self heightCellForIndexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"CellIdentifier";
    JrdMenuSectionCell *cell = (JrdMenuSectionCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[JrdMenuSectionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    return [self configureWithCell:cell IndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.didSelectedIndexBlock) {
        self.didSelectedIndexBlock(indexPath.row);
    }
    
}

#pragma mark - Configure TableCell

- (CGFloat)heightCellForIndexPath:(NSIndexPath *)indexPath {
    
    return [JrdMenuSectionCell getCellHeight];
    
}

- (JrdMenuSectionCell *)configureWithCell:(JrdMenuSectionCell *)cell IndexPath:(NSIndexPath *)indexPath {
    cell.imageName = self.sectionImageNameArray[indexPath.row];
    cell.title     = self.sectionTitleArray[indexPath.row];
    cell.badge = nil;
    return cell;
}


#pragma mark - Notifications

- (void)didReceiveThemeChangeNotification {
    
    [self.tableView reloadData];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:[JrdSettingManager manager].selectedSectionIndex inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
    self.avatarImageView.alpha = kSetting.imageViewAlphaForCurrentTheme;
    self.divideImageView.alpha = kSetting.imageViewAlphaForCurrentTheme;

}

- (void)didReceiveUpdateCheckInBadgeNotification {
    
    [self.tableView reloadData];
//    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.sectionTitleArray.count - 1 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
    
}

@end
